<template>
  <div class="update-checker">
    <div class="update-status">
      <h3>自动更新</h3>
      <div class="status-info">
        <p>当前版本: {{ currentVersion }}</p>
        <p v-if="updateInfo">最新版本: {{ updateInfo.version }}</p>
        <p v-if="downloadProgress">下载进度: {{ downloadProgress.percent.toFixed(1) }}%</p>
        <p v-if="downloadPath">下载路径: {{ downloadPath }}</p>
      </div>
      
      <div class="update-actions">
        <button 
          @click="checkForUpdates" 
          :disabled="isChecking"
          class="btn btn-primary"
        >
          {{ isChecking ? '检查中...' : '检查更新' }}
        </button>
        
        <button 
          v-if="updateAvailable && !isDownloading" 
          @click="downloadUpdate" 
          class="btn btn-success"
        >
          下载更新
        </button>
        
        <button 
          v-if="isDownloading" 
          disabled 
          class="btn btn-warning"
        >
          下载中... {{ downloadProgress ? downloadProgress.percent.toFixed(1) + '%' : '' }}
        </button>
        
        <button 
          v-if="updateDownloaded" 
          @click="installUpdate" 
          class="btn btn-danger"
        >
          安装更新
        </button>
      </div>
      
      <div v-if="error" class="error-message">
        <p>错误: {{ error }}</p>
      </div>
      
      <div v-if="message" class="info-message">
        <p>{{ message }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const currentVersion = ref('1.0.0');
const updateInfo = ref(null);
const updateAvailable = ref(false);
const updateDownloaded = ref(false);
const isChecking = ref(false);
const isDownloading = ref(false);
const downloadProgress = ref(null);
const error = ref(null);
const message = ref(null);
const downloadPath = ref(null);

function handleUpdateStatus(data) {
  const { type, data: statusData } = data;
  
  switch (type) {
    case 'checking-for-update':
      isChecking.value = true;
      message.value = '正在检查更新...';
      error.value = null;
      break;
      
    case 'update-available':
      isChecking.value = false;
      updateAvailable.value = true;
      updateInfo.value = statusData;
      message.value = `发现新版本: ${statusData.version}`;
      error.value = null;
      break;
      
    case 'update-not-available':
      isChecking.value = false;
      message.value = '当前已是最新版本';
      error.value = null;
      break;
      
    case 'download-progress':
      isDownloading.value = true;
      downloadProgress.value = statusData;
      message.value = `下载进度: ${statusData.percent.toFixed(1)}%`;
      break;
      
    case 'update-downloaded':
      isDownloading.value = false;
      updateDownloaded.value = true;
      message.value = '更新下载完成，可以安装';
      error.value = null;
      break;
      
    case 'update-error':
      isChecking.value = false;
      isDownloading.value = false;
      error.value = statusData;
      message.value = null;
      break;
  }
}

function setupUpdateListeners() {
  if (window.electronAPI && window.electronAPI.updater) {
    window.electronAPI.updater.onUpdateStatus((data) => {
      handleUpdateStatus(data);
    });
  }
}

async function checkForUpdates() {
  try {
    isChecking.value = true;
    error.value = null;
    message.value = '正在检查更新...';
    
    const result = await window.electronAPI.updater.checkForUpdates();
    
    if (!result.success) {
      error.value = result.error || '检查更新失败';
    }
  } catch (err) {
    error.value = err.message || '检查更新时发生错误';
  } finally {
    isChecking.value = false;
  }
}

async function downloadUpdate() {
  try {
    isDownloading.value = true;
    error.value = null;
    message.value = '开始下载更新...';
    
    const result = await window.electronAPI.updater.downloadUpdate();
    
    if (!result.success) {
      error.value = result.error || '下载更新失败';
      isDownloading.value = false;
    }
  } catch (err) {
    error.value = err.message || '下载更新时发生错误';
    isDownloading.value = false;
  }
}

async function installUpdate() {
  try {
    error.value = null;
    message.value = '正在安装更新...';
    
    const result = await window.electronAPI.updater.installUpdate();
    
    if (!result.success) {
      error.value = result.error || '安装更新失败';
    }
  } catch (err) {
    error.value = err.message || '安装更新时发生错误';
  }
}

function getCurrentVersion() {
  // 通过 Electron API 从主进程获取当前版本号
  window.electronAPI.updater.getAppVersion().then(version => {
    currentVersion.value = version || '未知版本';
  }).catch(() => {
    currentVersion.value = '未知版本';
  });
}

function getDownloadPath() {
  // 获取更新下载路径
  window.electronAPI.updater.getUpdateDownloadPath().then(pathInfo => {
    downloadPath.value = pathInfo.downloadPath;
  }).catch(() => {
    downloadPath.value = '获取失败';
  });
}

onMounted(() => {
  setupUpdateListeners();
  getCurrentVersion();
  getDownloadPath();
});

onBeforeUnmount(() => {
  // 清理监听器
  if (window.electronAPI && window.electronAPI.updater) {
    window.electronAPI.updater.removeUpdateStatusListener();
  }
});
</script>

<style scoped>
.update-checker {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
  max-width: 500px;
  margin: 20px auto;
}

.update-status h3 {
  margin-top: 0;
  color: #333;
  text-align: center;
}

.status-info {
  margin: 15px 0;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
}

.status-info p {
  margin: 5px 0;
  font-size: 14px;
}

.update-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
  margin: 15px 0;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #0056b3;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background-color: #1e7e34;
}

.btn-warning {
  background-color: #ffc107;
  color: #212529;
}

.btn-warning:hover:not(:disabled) {
  background-color: #e0a800;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background-color: #c82333;
}

.error-message {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  color: #721c24;
}

.info-message {
  margin-top: 15px;
  padding: 10px;
  background-color: #d1ecf1;
  border: 1px solid #bee5eb;
  border-radius: 4px;
  color: #0c5460;
}
</style> 